<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { reqUserAddOrUpdate } from '@/api/user'
import useUserStore from '@/store/modules/user.ts'
import { OPERATION_TYPE } from '@/api/type.ts'
import type { User } from '@/api/user/type.ts'

const props = defineProps<{
  operate?: OPERATION_TYPE
}>()

const $emit = defineEmits(['get-user-list'])

const userStore = useUserStore()

const show = ref<boolean>(false)
const setShow = (val: boolean) => {
  show.value = val
}

const userParams = reactive<User>({
  id: '',
  name: '',
  username: '',
  password: '',
})

const userFormRef = ref<FormInstance>()

let oldUsername: string = '' // 修改前的用户名

const validateName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户姓名至少五位'))
  }
}

const validateUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名称至少五位'))
  }
}

const validatePassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('密码至少六位'))
  }
}

const rules = reactive<FormRules<User>>({
  name: [{ validator: validateName, trigger: 'blur' }],
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
})

const resetUserForm = () => {
  Object.assign(userParams, {
    id: '',
    name: '',
    username: '',
    password: '',
  })
}

const setUserForm = (user: User) => {
  oldUsername = user?.username as string
  Object.assign(userParams, user)
}

const onConfirm = async () => {
  try {
    await userFormRef.value?.validate()

    const { code, message } = await reqUserAddOrUpdate(userParams)
    if (code == 200) {
      ElMessage.success(operateName.value + '成功')

      // 修改当前账号，退出重新登录
      if (oldUsername == userStore?.username) {
        ElMessage.warning('修改当前账号，3秒后跳转到登录页，请重新登录')
        setTimeout(() => {
          userStore.clear()
          window.location.reload()
        }, 3000)
      }

      // 添加跳到首页，修改留在当前页
      if (props.operate == OPERATION_TYPE.ADD) {
        $emit('get-user-list', 1)
      } else {
        $emit('get-user-list')
      }
      resetUserForm()
      show.value = false
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    err.message && ElMessage.error(err.message)
  }
}

const onCancel = () => {
  resetUserForm()
  userFormRef.value?.clearValidate()
  show.value = false
}

const operateName = computed(() => {
  return props.operate == OPERATION_TYPE.ADD ? '添加' : '修改'
})
defineExpose({
  setShow,
  setUserForm,
})
</script>

<template>
  <el-drawer v-model="show">
    <template #header>
      <h4>{{ operateName }}用户</h4>
    </template>
    <template #default>
      <el-form
        :model="userParams"
        :rules="rules"
        ref="userFormRef"
        label-width="80"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input
            v-model="userParams.name"
            placeholder="请输入用户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input
            v-model="userParams.username"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <!-- 添加用户时才显示密码输入，通过user.id来判断 -->
        <el-form-item v-if="!userParams.id" label="密码" prop="password">
          <el-input
            v-model="userParams.password"
            type="password"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="onConfirm">确认</el-button>
      <el-button @click="onCancel">取消</el-button>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss"></style>
